import React from 'react'
import {Select, Form} from 'antd';
import jsonp from 'fetch-jsonp';
import querystring from 'querystring';
import axios from '../../components/Engineering/axios'


import qs from 'qs'; //或者是querystringify
//todo kim-stamp qs用来解析     var obj = qs.parse('a=c'); assert.deepEqual(obj, { a: 'b' }   var str = qs.stringify(obj);  assert.equal(str, 'a=c');
//todo qs.parse('foo=bar&bar=foo') --->{ foo: 'bar', bar: 'foo' }    qs.parse('foo&bar=foo') ---> { foo: '', bar: 'foo' }    qs.stringify({ foo: bar });       // foo=bar
// qs.stringify({ foo: bar }, true); ---> ?foo=bar
// qs.stringify({ foo: bar }, '&');  ---> &foo=bar
// qs.stringify({ foo: '' }, '&');   ---> &foo=

import assert from 'assert';                 //todo kim-stamp qs用来断言
const {Option} = Select;
const FormItem = Form.Item;


function fetch({url, keywords}, callback) {
  let timeout,
    currentKeywords;
  if (timeout) {
    clearTimeout(timeout);
    timeout = null;
  }
  currentKeywords = keywords;

  function fake() {

    const str = querystring.encode({
      code: 'utf-8',
      q: keywords,
    });
    jsonp(`${url}?${str}`)
      .then(response => response.json()) //会给回一个 Promise对象
      .then(res => {
        if (currentKeywords === keywords) {
          const {result} = res;
          const data = [];
          result.forEach(item => {
            data.push({
              keywords: item[0],
              text: item[0],
            });
          });
          callback(data);
        }
      });
  }

  timeout = setTimeout(fake, 100);
}


export default class SearchInput extends React.Component {
  state = {
    data: [],
    value: undefined,
  };


  handleSearch = value => {
    if (value) {
      fetch(value, data => this.setState({data}));
    } else {
      this.setState({data: []});
    }
  };

  handleChange = value => {
    this.setState({value});
  };


  render() {
    const {url} = this.props
    const options = this.state.data.map(item => <Option key={item.keywords} value={item.value}>{item.text}</Option>)

    return (
      <Select
        allowClear
        showSearch
        autoFocus
        placeholder={this.props.placeholder || '请输入'}
        // style={this.props.style}
        defaultActiveFirstOption={false}
        showArrow={false}
        filterOption={false}
        onSearch={(keywords) => fetch({url, keywords}, data => this.setState({data}))}
        onChange={(keywords, options) => {
          alert(544554);
          this.setState({keywords});
          this.props.onChange && this.props.onChange(keywords);
        }}
        notFoundContent={null}
      >
        {this.state.data.map(item => <Option key={item.keywords} value={item.value}>{item.text}</Option>)}
        {options}
        {this.props.children}
      </Select>
    )
  }
}
